﻿using Newtonsoft.Json;
using RemoteTool.Business.Tools.Helper;
using RemoteTool.Data;
using RemoteTool.Data.Model;
using RemoteTool.Shared;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RemoteTool.Service
{
    public class WebApiService : IWebApiService
    {
        public string Token { get; set; }
        public string Url { get => CfgManager.SysConfig.ServerUrl; }
        public ConfigManager CfgManager { get; set; }
        public WebApiService(ConfigManager configManager)
        {
            CfgManager = configManager;
        }

        public async Task<ApiResult<string>> GetAccessTokenAsync(string userName, string password)
        {
            var result = new ApiResult<string>() { success = false };
            var client = new RestClient($"{Url}/api/RemoteTool/GetToken");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            var body = JsonConvert.SerializeObject(new { userName = userName, password = password });
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = await client.ExecuteAsync(request);
            Console.WriteLine(response.Content);
            if (response.IsSuccessful)
            {
                result.success = true;
                result.data = response.Content;
                Token = response.Content.Trim(new char[] { '"' });
            }
            else
            {
                result.success = false;
                result.statusCode = (int)response.StatusCode;
                result.message = response.ErrorMessage;
            }
            return result;
        }

        public async Task<ApiResult<UserInfo>> GetUserInfoAsync(string userName)
        {
            var apiResult = new ApiResult<UserInfo>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/GetUserInfo?userName={userName}");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", $"Bearer {Token}");
                request.AlwaysMultipartFormData = true;
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<UserInfo>>(response.Content);

                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = "查询失败";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"查询userName={userName}的用户信息异常->{ex.Message}");
            }
            return apiResult;
        }

        public async Task<ApiResult<DeviceInfo>> AddDeviceInfoAsync(DeviceInfo info)
        {
            var apiResult = new ApiResult<DeviceInfo>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/AddDeviceInfo");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", $"Bearer {Token}");
                request.AddHeader("Content-Type", "application/json");
                var body = JsonConvert.SerializeObject(info);
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<DeviceInfo>>(response.Content);
                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = "新增设备信息失败";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"新增设备信息异常->{ex.Message}");
            }
            return apiResult;
        }

        public async Task<ApiResult<DeviceInfo>> DeleteDeviceInfoAsync(string guidCode)
        {
            var apiResult = new ApiResult<DeviceInfo>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/DeleteDeviceInfo?guidCode={guidCode}");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AlwaysMultipartFormData = true;
                request.AddHeader("Authorization", $"Bearer {Token}");
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<DeviceInfo>>(response.Content);
                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = $"删除设备信息失败->{response.Content}";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"删除guid={guidCode}的设备信息异常->{ex.Message}");
            }
            return apiResult;
        }

        public async Task<ApiResult<DeviceInfo>> ModifyDeviceInfoAsync(DeviceInfo info)
        {
            var apiResult = new ApiResult<DeviceInfo>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/ModifyDeviceInfo");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", $"Bearer {Token}");
                request.AddHeader("Content-Type", "application/json");
                var body = JsonConvert.SerializeObject(info);
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<DeviceInfo>>(response.Content);

                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = $"修改设备信息失败->{response.Content}";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"修改设备信息异常->{ex.Message}");
            }
            return apiResult;
        }

        public async Task<ApiResult<List<DeviceInfo>>> SearchDeviceInfoAsync(string keyword)
        {
            var apiResult = new ApiResult<List<DeviceInfo>>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/SearchDeviceInfo?keyword={keyword}");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", $"Bearer {Token}");
                request.AlwaysMultipartFormData = true;
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<List<DeviceInfo>>>(response.Content);

                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = $"查询失败->{response.Content}";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"查询keyword={keyword}的设备信息异常->{ex.Message}");
            }
            return apiResult;
        }

        public async Task<ApiResult<List<DeviceInfo>>> DownloadDeviceInfosAsync()
        {
            var apiResult = new ApiResult<List<DeviceInfo>>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/DownloadDeviceInfos");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", $"Bearer {Token}");
                request.AlwaysMultipartFormData = true;
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<List<DeviceInfo>>>(response.Content);

                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = $"下载所有设备信息失败->{response.Content}";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"下载所有设备信息异常->{ex.Message}");
            }
            return apiResult;
        }

        public async Task<ApiResult<string>> UploadDeviceInfosAsync(List<DeviceInfo> deviceInfos)
        {
            var apiResult = new ApiResult<string>();
            try
            {
                var client = new RestClient($"{Url}/api/RemoteTool/UploadDeviceInfos");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", $"Bearer {Token}");
                request.AddHeader("Content-Type", "application/json");
                var body = JsonConvert.SerializeObject(deviceInfos);
                request.AddParameter("application/json", body, ParameterType.RequestBody);
                IRestResponse response = await client.ExecuteAsync(request);
                Console.WriteLine(response.Content);
                if (response.IsSuccessful)
                {
                    apiResult = JsonConvert.DeserializeObject<ApiResult<string>>(response.Content);
                }
                else
                {
                    apiResult.success = false;
                    apiResult.message = "上传设备信息失败";
                    apiResult.statusCode = (int)response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"上传设备信息异常->{ex.Message}");
            }
            return apiResult;
        }
    }
}
